<template>
  <div class="medical-form">
    <el-card shadow="never">
      <template #header>
        <div class="page-header">
          <h2>{{ isEdit ? '编辑医疗记录' : '添加医疗记录' }}</h2>
          <el-button @click="$router.back()">返回</el-button>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        class="form-container"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="宠物编号" prop="petId">
              <el-input v-model.number="formData.petId" placeholder="请输入宠物编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="诊断日期" prop="diagnosisDate">
              <el-date-picker
                v-model="formData.diagnosisDate"
                type="date"
                placeholder="选择诊断日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="疾病名称" prop="medicalName">
              <el-input v-model="formData.medicalName" placeholder="请输入疾病名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="症状描述" prop="symptoms">
              <el-input v-model="formData.symptoms" type="textarea" :rows="3" placeholder="请输入症状描述" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="诊断结果" prop="medicalResult">
              <el-input v-model="formData.medicalResult" type="textarea" :rows="3" placeholder="请输入诊断结果" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="治疗方案" prop="treatmentPlan">
              <el-input v-model="formData.treatmentPlan" type="textarea" :rows="3" placeholder="请输入治疗方案" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用药记录" prop="medication">
              <el-input v-model="formData.medication" type="textarea" :rows="3" placeholder="请输入用药记录" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="复诊日期" prop="followupDate">
              <el-date-picker
                v-model="formData.followupDate"
                type="date"
                placeholder="选择复诊日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="费用(元)" prop="cost">
          <el-input-number
            v-model="formData.cost"
            :min="0"
            :precision="2"
            placeholder="请输入费用"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="治疗中" value="TREATING" />
            <el-option label="已治愈" value="CURED" />
            <el-option label="需要复查" value="FOLLOW_UP" />
            <el-option label="转诊" value="REFERRED" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="loading">
            {{ isEdit ? '更新' : '保存' }}
          </el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { medicalApi } from '@/api'
import type { Medical } from '@/types'

const router = useRouter()
const route = useRoute()

const formRef = ref<FormInstance>()
const loading = ref(false)

// 判断是否为编辑模式
const isEdit = computed(() => {
  return route.params.id !== undefined
})

// 表单数据
const formData = reactive<Medical>({
  medicalId: undefined,
  petId: undefined,
  staffId: 0,
  diagnosisDate: '',
  medicalName: '',
  symptoms: '',
  medicalResult: '',
  treatmentPlan: '',
  medication: '',
  cost: 0,
  status: 'TREATING',
  followupDate: ''
})

// 表单验证规则
const formRules: FormRules = {
  petId: [
    { required: true, message: '请输入宠物编号', trigger: 'blur' }
  ],
  diagnosisDate: [
    { required: true, message: '请选择诊断日期', trigger: 'change' }
  ],
  medicalName: [
    { required: true, message: '请输入疾病名称', trigger: 'blur' }
  ],
  symptoms: [
    { required: true, message: '请输入症状描述', trigger: 'blur' }
  ],
  medicalResult: [
    { required: true, message: '请输入诊断结果', trigger: 'blur' }
  ],
  treatmentPlan: [
    { required: true, message: '请输入治疗方案', trigger: 'blur' }
  ],
  cost: [
    { required: true, message: '请输入费用', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  followupDate: [
    { required: true, message: '请选择复诊日期', trigger: 'change' }
  ]
}

// 获取医疗记录详情
const fetchMedicalDetail = async (id: number) => {
  try {
    const response = await medicalApi.getById(id)
    if (response.code === 200) {
      Object.assign(formData, response.data)
    } else {
      ElMessage.error(response.message || '获取医疗记录详情失败')
    }
  } catch (error) {
    console.error('获取医疗记录详情失败:', error)
    ElMessage.error('获取医疗记录详情失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    // 准备提交的数据
    const submitData = { ...formData }
    
    // 如果是添加操作，删除ID字段
    if (!isEdit.value) {
      delete submitData.medicalId
    }
    
    console.log('表单数据:', formData)
    console.log('是否为编辑模式:', isEdit.value)
    console.log('medicalId:', formData.medicalId)
    
    console.log('提交的医疗数据:', submitData)
    console.log('提交的医疗数据JSON:', JSON.stringify(submitData, null, 2))
    
    let response
    if (isEdit.value) {
      console.log('调用更新接口...')
      response = await medicalApi.update(submitData)
      console.log('更新接口响应:', response)
    } else {
      console.log('调用添加接口...')
      response = await medicalApi.add(submitData)
      console.log('添加接口响应:', response)
    }
    
    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
      router.push('/medical-manage/medical')
    } else {
      console.error('操作失败，响应:', response)
      ElMessage.error(response.message || response.msg || '操作失败')
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    ElMessage.error('提交失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 取消操作
const handleCancel = () => {
  router.push('/medical-manage/medical')
}

onMounted(() => {
  if (isEdit.value) {
    const medicalId = Number(route.params.id)
    if (medicalId) {
      fetchMedicalDetail(medicalId)
    }
  }
})
</script>

<style scoped>
.medical-form {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.form-container {
  max-width: 800px;
  margin: 0 auto;
}
</style> 